﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MM.Commmon.UI;
using MM.Common.Message;
using System.Net.Sockets;
using MM.Common.Base;
using System.Net;
using DevExpress.XtraTreeList.Nodes;

namespace MMTJ
{
    public partial class FrmMessageClient : FrmBase
    {
        private string errorMessage = "";
        private bool isConnect;
        private string serverIP = "127.0.0.1";
        private int serverPort = 0x3e8;
        private ClientInfo clientInfo;
        private Socket clientSocket;
        private byte[] byteData = new byte[0x400];

        public FrmMessageClient(string server, int port)
        {
            InitializeComponent();
            clientInfo = new ClientInfo();
            if (server != "")
            {
                serverIP = server;
            }
            if (port > 0)
            {
                serverPort = port;
            }
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        private void AddClientInfo(string clientinfo)
        {
            int index = clientinfo.IndexOf("|");
            int num2 = int.Parse(clientinfo.Substring(0, index));
            clientinfo = clientinfo.Substring(index + 1);
            index = clientinfo.IndexOf("|");
            int num3 = int.Parse(clientinfo.Substring(0, index));
            clientinfo = clientinfo.Substring(index + 1);
            index = clientinfo.IndexOf("|");
            string str = clientinfo.Substring(0, index);
            clientinfo = clientinfo.Substring(index + 1);
            index = clientinfo.IndexOf("|");
            string str2 = clientinfo.Substring(0, index);
            string str3 = clientinfo.Substring(index + 1);
            this.tlList.AppendNode(new object[] { num2, str2, num3, str, str3 }, this.tlList.Nodes.ParentNode);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.txtChatBox.Text = "";
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (this.ckb_BoardCast.Checked)
            {
                this.SendBoardCast(this.txtMessage.Text);
            }
            else
            {
                foreach (TreeListNode node in this.tlList.Nodes)
                {
                    if (node.Selected)
                    {
                        this.SendMessage(node[0].ToString() + "|" + this.txtMessage.Text);
                    }
                }
            }
            this.txtMessage.Text = "";
        }

        private void FrmMessageClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            base.Visible = false;
            if (SystemInfo.MessageDataServer.MessageStatus != EMessageStatus.Disconnect)
            {
                SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Wait;
            }
            e.Cancel = true;
        }

        private MessageData GetClientInfo()
        {
            return new MessageData { Client = { ClientMessageID = this.clientInfo.ClientMessageID, ClientID = this.clientInfo.ClientID, ClientName = this.clientInfo.ClientName, ClientIP = this.clientInfo.ClientIP, SystemCode = this.clientInfo.SystemCode } };
        }


        public bool Init()
        {
            bool flag = false;
            if (base.Init())
            {
                try
                {
                    this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(this.serverIP), this.serverPort);
                    this.clientSocket.BeginConnect(remoteEP, new AsyncCallback(this.OnConnect), null);
                    this.txtChatBox.Text = "";
                    this.timer1.Start();
                    flag = true;
                }
                catch (Exception exception)
                {
                    if (!this.clientSocket.Connected)
                    {
                        SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Disconnect;
                    }
                    this.errorMessage = "连接出错:" + exception.StackTrace + "\r\n" + exception.Message;
                }
            }
            return flag;
        }

        public void Logout()
        {
            try
            {
                this.SendLogout();
                this.clientSocket.Close();
                SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.None;
            }
            catch (Exception exception)
            {
                string text = this.txtChatBox.Text;
                this.txtChatBox.Text = text + exception.StackTrace + "\r\n" + exception.Message + "\r\n";
            }
        }

        private void OnConnect(IAsyncResult ar)
        {
            try
            {
                this.clientSocket.EndConnect(ar);
                this.clientInfo.ClientIP = SystemInfo.ComputerIp;
                this.clientInfo.SystemCode = SystemInfo.SystemCode;
                this.clientInfo.ClientID = SystemInfo.OperId;
                this.clientInfo.ClientMessageID = 0;
                this.clientInfo.ClientName = SystemInfo.OperName;
                this.clientInfo.ClientRole = SystemInfo.OperRoleList;
                MessageData clientInfo = this.GetClientInfo();
                clientInfo.MessageInfo = SystemInfo.OperDepartName + "|" + SystemInfo.OperGroupName + "|" + SystemInfo.OperRoleList;
                clientInfo.Command = MessageCommand.Register;
                try
                {
                    byte[] buffer = clientInfo.ToByte();
                    this.clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(this.OnRegister), null);
                }
                catch (Exception exception)
                {
                    this.errorMessage = "发送出错:" + exception.StackTrace + "\r\n" + exception.Message;
                    string text = this.txtChatBox.Text;
                    this.txtChatBox.Text = text + exception.StackTrace + "\r\n" + exception.Message + "\r\n";
                }
            }
            catch (Exception exception2)
            {
                if (!this.clientSocket.Connected)
                {
                    SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Disconnect;
                }
                this.errorMessage = "连接出错:" + exception2.StackTrace + "\r\n" + exception2.Message;
            }
        }

        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                string[] strArray;
                int num;
                this.clientSocket.EndReceive(ar);
                MessageData data = new MessageData(this.byteData);
                switch (data.Command)
                {
                    case MessageCommand.Register:
                        {
                            this.clientInfo.ClientMessageID = data.Client.ClientMessageID;
                            if (data.MessageInfo == null)
                            {
                                goto Label_00B0;
                            }
                            int clientID = data.Client.ClientID;
                            strArray = data.MessageInfo.Split(new char[] { '*' });
                            num = 0;
                            goto Label_00A8;
                        }
                    case MessageCommand.Login:
                        this.AddClientInfo(data.MessageInfo);
                        goto Label_019E;

                    case MessageCommand.Logout:
                        {
                            TreeListNode node = this.tlList.FindNodeByFieldValue("MESSAGE_ID", data.Client.ClientMessageID);
                            if (node != null)
                            {
                                this.tlList.Nodes.Remove(node);
                            }
                            goto Label_019E;
                        }
                    case MessageCommand.Function:
                        {
                            int index = data.MessageInfo.IndexOf(":");
                            if (index <= 0)
                            {
                                goto Label_019E;
                            }
                            string code = data.MessageInfo.Substring(0, index);
                            string body = data.MessageInfo.Substring(index + 1);
                            ReceiveFunctionInformation item = new ReceiveFunctionInformation(code, body);
                            lock (SystemInfo.MessageDataServer.ReceiveFunctionInformation)
                            {
                                SystemInfo.MessageDataServer.ReceiveFunctionInformation.Enqueue(item);
                                goto Label_019E;
                            }
                            goto Label_0179;
                        }
                    case MessageCommand.Message:
                        SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.New;
                        goto Label_019E;

                    case MessageCommand.Boardcast:
                        SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.New;
                        goto Label_019E;

                    case MessageCommand.Call:
                        goto Label_0179;

                    default:
                        goto Label_019E;
                }
            Label_009B:
                this.AddClientInfo(strArray[num]);
                num++;
            Label_00A8:
                if (num < (strArray.Length - 1))
                {
                    goto Label_009B;
                }
            Label_00B0:
                this.SendLogin();
                goto Label_019E;
            Label_0179:
                SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Call;
            Label_019E:
                if ((data.MessageInfo != null) && (((data.Command == MessageCommand.Call) || (data.Command == MessageCommand.Message)) || (data.Command == MessageCommand.Boardcast)))
                {
                    this.txtChatBox.Text = this.txtChatBox.Text + data.MessageInfo + "\r\n";
                    foreach (TreeListNode node2 in this.tlList.Nodes)
                    {
                        if (int.Parse(node2[0].ToString()) == data.Client.ClientMessageID)
                        {
                            this.tlList.Nodes.TreeList.SetFocusedNode(node2);
                            break;
                        }
                    }
                }
                this.byteData = new byte[0x400];
                this.clientSocket.BeginReceive(this.byteData, 0, this.byteData.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
            }
            catch (Exception exception)
            {
                if (!this.clientSocket.Connected)
                {
                    SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Disconnect;
                }
                this.errorMessage = "接收出错:" + exception.StackTrace + "\r\n" + exception.Message;
                string text = this.txtChatBox.Text;
                this.txtChatBox.Text = text + exception.StackTrace + "\r\n" + exception.Message + "\r\n";
            }
        }

        private void OnRegister(IAsyncResult ar)
        {
            try
            {
                this.byteData = new byte[0x400];
                this.clientSocket.BeginReceive(this.byteData, 0, this.byteData.Length, SocketFlags.None, new AsyncCallback(this.OnReceive), null);
                SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Wait;
            }
            catch (Exception exception)
            {
                if (!this.clientSocket.Connected)
                {
                    SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Disconnect;
                }
                this.errorMessage = "发送出错:" + exception.StackTrace + "\r\n" + exception.Message;
                string text = this.txtChatBox.Text;
                this.txtChatBox.Text = text + exception.StackTrace + "\r\n" + exception.Message + "\r\n";
            }
        }

        private void OnSend(IAsyncResult ar)
        {
            try
            {
                this.clientSocket.EndSend(ar);
            }
            catch (Exception exception)
            {
                if (!this.clientSocket.Connected)
                {
                    SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Disconnect;
                }
                this.errorMessage = "发送出错:" + exception.StackTrace + "\r\n" + exception.Message;
                string text = this.txtChatBox.Text;
                this.txtChatBox.Text = text + exception.StackTrace + "\r\n" + exception.Message + "\r\n";
            }
        }

        private void Send(MessageData sendmessage)
        {
            try
            {
                byte[] buffer = sendmessage.ToByte();
                this.clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(this.OnSend), null);
            }
            catch (Exception exception)
            {
                if (!this.clientSocket.Connected)
                {
                    SystemInfo.MessageDataServer.MessageStatus = EMessageStatus.Disconnect;
                }
                this.errorMessage = "发送出错:" + exception.StackTrace + "\r\n" + exception.Message;
                string text = this.txtChatBox.Text;
                this.txtChatBox.Text = text + exception.StackTrace + "\r\n" + exception.Message + "\r\n";
            }
        }

        private void SendAddFunction(string functioncode)
        {
            MessageData clientInfo = this.GetClientInfo();
            clientInfo.MessageInfo = functioncode;
            clientInfo.Command = MessageCommand.AddFunction;
            this.Send(clientInfo);
        }

        private void SendBoardCast(string message)
        {
            MessageData clientInfo = this.GetClientInfo();
            clientInfo.MessageInfo = message;
            clientInfo.Command = MessageCommand.Boardcast;
            this.Send(clientInfo);
        }

        private void SendDelFunction(string functioncode)
        {
            MessageData clientInfo = this.GetClientInfo();
            clientInfo.MessageInfo = functioncode;
            clientInfo.Command = MessageCommand.DelFunction;
            this.Send(clientInfo);
        }

        private void SendFunction(string functioncode, string message)
        {
            MessageData clientInfo = this.GetClientInfo();
            if (functioncode == "###")
            {
                clientInfo.Command = MessageCommand.Call;
                clientInfo.MessageInfo = message;
            }
            else
            {
                clientInfo.MessageInfo = functioncode + "|" + message;
                clientInfo.Command = MessageCommand.Function;
            }
            this.Send(clientInfo);
        }

        private void SendLogin()
        {
            MessageData clientInfo = this.GetClientInfo();
            clientInfo.MessageInfo = null;
            clientInfo.Command = MessageCommand.Login;
            this.Send(clientInfo);
        }

        private void SendLogout()
        {
            MessageData clientInfo = this.GetClientInfo();
            clientInfo.MessageInfo = null;
            clientInfo.Command = MessageCommand.Logout;
            this.Send(clientInfo);
        }

        private void SendMessage(string message)
        {
            MessageData clientInfo = this.GetClientInfo();
            clientInfo.MessageInfo = message;
            clientInfo.Command = MessageCommand.Message;
            this.Send(clientInfo);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (SystemInfo.MessageDataServer.MessageStatus != EMessageStatus.Disconnect)
            {
                TimeSpan span = new TimeSpan(DateTime.Now.Ticks);
                lock (SystemInfo.MessageDataServer.SendMessage)
                {
                    foreach (SendMessage message in SystemInfo.MessageDataServer.SendMessage)
                    {
                        TimeSpan ts = new TimeSpan(message.SendTime.Ticks);
                        TimeSpan span3 = span.Subtract(ts).Duration();
                        if (((span3.Days <= 0) && (span3.Hours <= 0)) && (span3.Minutes <= 5))
                        {
                            string code = message.Code;
                            if (code == null)
                            {
                                goto Label_00F1;
                            }
                            if (!(code == "+"))
                            {
                                if (code == "-")
                                {
                                    goto Label_00DF;
                                }
                                goto Label_00F1;
                            }
                            this.SendAddFunction(message.Body);
                        }
                        continue;
                    Label_00DF:
                        this.SendDelFunction(message.Body);
                        continue;
                    Label_00F1:
                        if (message.Code.Substring(0, 1) == "@")
                        {
                            int num = int.Parse(message.Code.Substring(1));
                            foreach (TreeListNode node in this.tlList.Nodes)
                            {
                                if (int.Parse(node[this.tlcEmployeeID].ToString()) == num)
                                {
                                    this.SendMessage(node[0].ToString() + "|" + message.Body);
                                }
                            }
                            continue;
                        }
                        this.SendFunction(message.Code, message.Body);
                    }
                    SystemInfo.MessageDataServer.SendMessage.Clear();
                }
            }
        }

        private void txtMessage_TextChanged(object sender, EventArgs e)
        {
            if (this.txtMessage.Text.Length == 0)
            {
                this.btnSend.Enabled = false;
            }
            else
            {
                this.btnSend.Enabled = true;
            }
        }

        // Properties
        public string ErrorMessage
        {
            get
            {
                return this.errorMessage;
            }
        }

        public bool IsConnect
        {
            get
            {
                return this.isConnect;
            }
        }

        public string ServerIP
        {
            get
            {
                return this.serverIP;
            }
            set
            {
                this.serverIP = value;
            }
        }

        public int ServerPort
        {
            get
            {
                return this.serverPort;
            }
            set
            {
                this.serverPort = value;
            }
        }

    }
}
